<script setup>
import { onMounted, nextTick, ref, reactive, watch } from 'vue'
import { getUserList, updateUser, addUser, getRoleList, delUser } from './system'
import { cloneDeep } from 'lodash-es';
import { filePreview } from '../forecast/fore';
import { ElMessage } from 'element-plus';
import { View, Hide } from '@element-plus/icons-vue'
import { encrypt, decrypt } from '@/components/utils/tool.js'

onMounted(() => {
  handleGetUserList()
  getRoleList()
    .then(res => {
      roleList.value = res.data.data
    })
    .catch(err => {
      ElMessage.error(err)
    })
})

function formatTimestamp(timestamp) {
  const date = new Date(timestamp * 1000); // 将时间戳转换为毫秒数
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hour = String(date.getHours()).padStart(2, '0');
  const minute = String(date.getMinutes()).padStart(2, '0');
  const second = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
}

const handleGetUserList = () => {
  passSee.value = []
  getUserList()
    .then(res => {
      dataSource.value = res.data.data.map(item => {
        passSee.value.push(false)
        return {
          ...item,
          password: decrypt(item.password),
          role: item.role,
          status: item.status == 1 ? true : false
        }
      })
    })
    .catch(err => {
      ElMessage.error(err)
    })
}


const dataSource = ref([]),
  dialogAdd = ref(false),
  dialogTitle = ref('新增用户'),
  form = reactive({
    username: '',
    password: '',
    role: [],
    status: true,
    id: '',
    // createdAt: '',
    // updatedAt: ''
  }),
  roleList = ref([]);

const handleStatus = (value) => {
  updateUser({
    ...value,
    password: encrypt(value.password),
    status: value.status ? 1 : 0,
    errCount: 0
  })
    .then(res => {
      if (res.data.code == 200) {
        ElMessage.success('修改成功')
        handleGetUserList()
      }
    })
    .catch(err => {
      ElMessage.error(err)
    })
},
  handleAdd = () => {
    if (dialogTitle.value == '新增用户') {
      addUser({
        ...form,
        password: encrypt(form.password),
        role: form.role.map(v => {
          return {
            id: v,
          }
        }),
        status: form.status ? 1 : 0
      })
        .then(res => {
          if (res.data.code === 200) {
            ElMessage.success('添加成功')
            dialogAdd.value = false
            handleGetUserList()
          } else {
            ElMessage.error(res.data.message)
          }
        })
        .catch(err => {
          ElMessage.error(err)
        })
    } else {
      updateUser({
        ...form,
        password: encrypt(form.password),
        role: form.role.map(v => {
          return {
            id: v,
          }
        }),
        status: form.status ? 1 : 0
      })
        .then(res => {
          if (res.data.code === 200) {
            ElMessage.success('修改成功')
            dialogAdd.value = false
            handleGetUserList()
          } else {
            ElMessage.error(res.data.message)
          }
        })
        .catch(err => {
          ElMessage.error(err)
        })
    }
  },
  handleClose = () => {
    dialogAdd.value = false
    restForm()
  }

const handleDel = (item) => {
  delUser(item)
    .then(res => {
      if (res.data.code == 200) {
        ElMessage.success('删除成功')
        handleGetUserList()
      }
    })
    .catch(err => {
      ElMessage.error(err)
    })
}

const startEdit = (item) => {
  dialogAdd.value = true
  dialogTitle.value = '编辑用户'
  form.username = item.username
  form.password = item.password
  form.role = item.role.map(v => v.id)
  form.status = item.status
  form.id = item.id
  form.createdAt = item.createdAt
  form.admin = item.admin
  form.code = item.code
  // form.updatedAt = new Date().toLocaleString()
},
  startAdd = () => {
    dialogAdd.value = true
    dialogTitle.value = '新增用户'
    restForm()
  }

const restForm = () => {
  form.username = ''
  form.password = ''
  form.role = []
  form.status = true
  form.id = ''
  form.admin = ''
  form.code = ''
  // form.createdAt = new Date().toLocaleString()
  // form.updatedAt = new Date().toLocaleString()
}

const passSee = ref([])
//  @change="handleStatus(row)"

const validateInput = () => {
  // 只能输入数字，英文和符号
  form.password = form.password.replace(/[^\w\.\/]/ig, '')
}
</script>

<template>
  <div class="User">
    <div class="card_hook">
      <el-button style="width: 60px;" size="default" @click="startAdd">新增</el-button>
      <el-table :data="dataSource" style="width: 100%" height="100%">
        <el-table-column type="index" label="序号" width="70" />
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="password" label="密码">
          <template #default="{ row, $index }">
            <div style="display: flex;height: 100%;">
              <span v-if="passSee[$index]">{{ row.password }}</span>
              <span v-else>******</span>
              <div @click="passSee[$index] = !passSee[$index]"
                style="margin-left: 5px;cursor: pointer;display: flex;align-items: center;">
                <el-icon v-if="passSee[$index]">
                  <View />
                </el-icon>
                <el-icon v-else>
                  <Hide />
                </el-icon>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="role" label="角色">
          <template #default="{ row }">
            {{ row.role.map(v => {
              return v.roleName
            }).join(',') }}
          </template>
        </el-table-column>
        <el-table-column prop="code" label="签发编号">
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template #default="{ row }">
            <el-switch v-model="row.status" active-color="#13ce66" inactive-color="#ff4949" @change="handleStatus(row)" :disabled="row.admin=='1'" />
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间">
          <template #default="{ row }">
            <el-tag>{{ formatTimestamp(row.createdAt) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="updatedAt" label="更新时间">
          <template #default="{ row }">
            <el-tag type="success">{{ formatTimestamp(row.updatedAt) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="loginCount" label="登录次数" />
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="startEdit(row)">编辑</el-button>
            <el-popconfirm title="确定要删除该用户?" @confirm="handleDel(row)">
              <template #reference>
                <el-button type="danger" size="small" :disabled="row.admin=='1'" @click="">删除</el-button>
              </template>
            </el-popconfirm>

          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 1 -->
    <el-dialog v-model="dialogAdd" :title="dialogTitle" width="30%" :before-close="handleClose">
      <!-- 添加用户的表单 -->
      <el-form label-width="70px" :model="form">
        <el-form-item label="用户名">
          <el-input v-model="form.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="form.password" placeholder="请输入密码" @input="validateInput"></el-input>
        </el-form-item>
        <el-form-item label="角色">
          <!-- <el-select v-model="form.role" placeholder="请选择角色">
            <el-option v-for="item in roleList" :key="item.id" :label="item.roleName" :value="item.id"></el-option>
          </el-select> -->
          <el-select v-model="form.role" multiple placeholder="Select" style="width: 100%" :disabled="form.admin=='1'">
            <el-option v-for="item in roleList" :key="item.id" :label="item.roleName" :value="item.id" />
          </el-select>
        </el-form-item>
        <!-- 签发编号 -->
        <el-form-item label="签发编号">
          <el-input v-model="form.code" placeholder="请输入签发编号"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogAdd = false">取消</el-button>
          <el-button type="primary" @click="handleAdd">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style lang='less' scoped>
.User {
  width: 100%;
  height: 100%;
  padding: 7px;

  .card_hook {
    height: 100%;
    padding: 10px;
    overflow: auto;
    display: flex;
    flex-direction: column;

    .editable-row-operations a {
      margin-right: 8px;
    }
  }
}
</style>